// components/general_detail/general_detail.js
const req = require('../../utils/request');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    //明细表信息
    detail:{
      type: Object,
      value: {},
      observer(newVal){
        this.initData(newVal);
      }
    },
    //明细数据列表
    detailData: {
      type: Array,
      observer(val){
        // console.log(val);
        let inputData = [];
      }
    },
    //只读
    readonly: {
      type: Boolean,
      value: false
    },
    //主表映射明细表
    dtlMap: {
      type: Object,
      observer(val){
        // console.log(val);
      }
    },
    //主表数据
    mainReferenceData:{}
  },

  /**
   * 组件的初始数据
   */
  data: {
    detailInfo: {}, //明细表信息{is_open:是否展开，table_name:表名，table_id: 表id，layout: 明细表布局,detailData: []默认数据}
    fieldList: [], //布局中所有字段集合
    popupShow: false,
    rowData: [],
    delData: [],
    editIndex: -1, //明细当前编辑
    curEditData: null, //当前编辑数据
    inputData:[],
    system_id: wx.getStorageSync('system_id') || 800,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,

  },

  /**
   * 组件的方法列表
   */
  methods: {
    //初始化数据
    async initData(data){

      let delData = data.detailData || [],
        arr = [];
      wx.$each(delData,(i,item)=>{
        arr.push(item);
      });

      let setObj = {
        detailInfo: data,
        rowData: arr,
      };

      await wx.$getAuth(data.table_id).then(res=>{
        setObj.auth = res;
      });
      if (!setObj.auth.tableSee) {
        return
      }

      await this.getFieldAll(data.table_id);
      let layout = data && data.layout;

      if (layout[0]){
        let fieldList = [];
        wx.$each(layout,(i,item)=>{
          let fields = item.field;
          fields[0] && wx.$each(fields,(ind,ite)=>{
            let id = ite.field_id || ite.fieldName,
              opt = this.data.fieldInfo.find(item=>{
                if (item.type === 'picture'){
                  item.watermark = [{
                    content: '$time$',
                    font: '34px sans-serif',
                    lineWidth: 3,
                    position: {
                      bottom: 15,
                      left: 15
                    }
                  },
                    {
                      content: '$location$',
                      font: '28px sans-serif',
                      lineWidth: 3,
                      position: {
                        bottom: 60,
                        left: 15
                      }
                    },]
                }
                return item.field_id === id;
              });
            if (!opt){return}

            fields[ind] = opt;
            if (setObj.auth.fieldSee.indexOf(id)<0){
              fields[ind].isHide = true;
            }
            fieldList.push(fields[ind]);
          })
        });

        setObj.layout = layout;
        setObj.fieldList = fieldList;

      }
      this.setData(setObj)
    },
    //切换展开收起明细
    toggleDetail(){
      let key = 'detailInfo.is_open';
      this.setData({
        [key]: !this.data.detailInfo.is_open
      })
    },

    //新增明细
    newDetail(){
      if (!this.data.auth.tableAppend) {
        wx.$toast('抱歉，您没有权限新增该模块数据！');
        return
      }
      // this.setData({popupShow: true,editIndex: -1,curEditData: {entity:{...this.data.dtlMap,row_id: 0},details: []} || {},status: 'add'});
      this.setData({popupShow: true,editIndex: -1,curEditData: {},status: 'add'});
    },
    //取消新增
    newCancel(){
      this.setData({popupShow: false});
    },
    //编辑明细
    editDetail(e){
      if (!this.data.auth.tableEdit) {
        wx.$toast('抱歉，您没有权限编辑该模块数据！');
        return
      }
      let data = e.currentTarget.dataset,
        row = data.row,
        index = data.index;
      if (this.data.delData[index] || row.row_id == 0) {
        this.setData({
          curEditData: this.data.detailData[index],
          popupShow: true,
          editIndex: index,
          status: 'edit'
        })
      }else if (row) {
        this.getRowData(row).then(data=>{
          let key = 'delData['+ index +']',
            obj = {
              table_id: this.data.detailInfo.table_id,
              entitys: []
            };
          this.setData({
            [key]: data,
            curEditData: data,
            popupShow: true,
            editIndex: index
          })
        })
      }
      /*this.setData({
        curEditData: data,
        popupShow: true
      })*/
    },
    //删除明细
    delDetail(e){
      if (!this.data.auth.tableDelete) {
        wx.$toast('抱歉，您没有权限删除该模块数据！');
        return
      }
      let data = e.currentTarget.dataset,
        row = data.row,
        index = data.index,
        list = this.data.detailData,
        rid = row.row_id;
      wx.showModal({
        title: '提示',
        content: '确认删除该记录？',
        success: (res) => {
          if(res.confirm) {
            if (rid == 0){
              wx.$toast('删除成功！');
              this.triggerEvent('change', {isDelete: true,table_id: this.data.detailInfo.table_id,index: index});
              /*list.splice(index, 1);

              this.setData({
                detailData: list
              });*/
            } else {
              this.deleteData(rid).then(()=>{
                wx.$toast('删除成功！');
                /*list.splice(index, 1);
                wx.$toast('删除成功！');
                this.setData({
                  detailData: list
                });*/
                this.triggerEvent('change', {isDelete: true,table_id: this.data.detailInfo.table_id,index: index});
              });
            }
          }
        },
      })
    },
    //删除记录
    deleteData(rid){
      return new Promise(resolve => {
        wx.$post(3,'DynamicUpdate/dynamic_delete',{row_ids: rid.toString(),table_id: this.data.detailInfo.table_id}).then(res=>{
          if (res.errcode != 0)return;
          resolve();
        })
      })
    },

    //保存明细
    bindSave(e){
      wx.showLoading({mask: true});
      let detail = e.detail,
        index = this.data.editIndex,
        setObj = {
          popupShow: detail.isShow
        };
      let data = wx.$extend(detail.data);
      //明细显示的辅助核算值和提交的值格式不一样，需重新赋值
      if (detail.defData.assist_account_json) detail.defData.assist_account_json = data.entity.assist_account_json;

      data.entity = {...data.entity,...detail.defData};
      this.triggerEvent('change', {details: data,table_id: this.data.detailInfo.table_id,index: index});
      if (detail.isShow){ //保存并新增
        this.data.editIndex = -1;
        setObj.curEditData = {};
      }
      this.setData(setObj,()=>{
        wx.hideLoading( )
      });

    },

    getRowData(rowdata){
      let id = rowdata.row_id,
        url = 'DynamicQuery/query_dynamic_v2',
        post = {
          table_id: this.data.detailInfo.table_id,
          row_id: id
        };

      return new Promise(resolve => {
        wx.$post(3,url,post).then((res)=>{
          if (res.errcode != 0){
            resolve({entity: {row_id: id}});
            return;
          }
          let data = res.data.row && res.data.row[0] || [];

          let row = res.data.row;
          if (row && row[0]){
            let data = row[0];
            console.log(data);
            let mainData = data.entity && data.entity[0],
              detail1 = data.detail1,
              detail2 = data.detail2;
            mainData = {...mainData,...rowdata};
            let obj = {
              entity: mainData,
              details: []
            };
            if (detail1.entity && detail1.entity[0]){
              let arr = detail1.entity,
                entitys = [];
              wx.$each(arr,(i,item)=>{
                entitys.push({
                  entity: item,
                  details: []
                })
              });
              obj.details.push({
                table_id: detail1.table_id,
                entitys: entitys
              })
            }
            if (detail2.entity && detail2.entity[0]){
              let arr = detail2.entity,
                entitys = [];
              wx.$each(arr,(i,item)=>{
                entitys.push({
                  entity: item,
                  details: []
                })
              });
              obj.details.push({
                table_id: detail2.table_id,
                entitys: entitys
              })
            }
            resolve(obj);
          }else {
            resolve({entity: {row_id: id}});
          }
        })
      })
    },

    getFieldAll(entity,fieldid){
      let url = 'QX/PRO_select_field',
        post = {
          "table": entity,
          "fieldname": fieldid
        };
      if(this.data.fieldInfo){
        return
      }
      return new Promise(resolve => {
        wx.$post(4,url,post).then((res)=>{
          if (res.errcode != 0)return;
          let data = res.data.row;
          let exp = [];
          wx.$each(data,function (i,item) {
            if (item.computeExpress) {
              exp.push(item);
            }
          });
          this.setData({
            fieldInfo: data,
            expList: exp
          })
          resolve();
        });
      })
    },

    // 预览图片
    previewImg(e) {
      let { index, urls, } = e.currentTarget.dataset;
      let {  system_id,baseURL } = this.data,
        uploadImgs = urls && urls.split(','),
        imgs = [];
      //231215 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
      uploadImgs.forEach(item => {
        let name = item.substring(item.lastIndexOf('/')+1);
        imgs.push(`${baseURL}/files/${system_id}/${name}`)
      });
      //231215 end
      wx.previewImage({
        current: imgs[index],
        urls: imgs
      })
    },

  }
})
